layui.define(['element', 'api', 'fast_config', 'amis', 'utils', 'tab'], function (exports) {
    "use strict";

    /**
     * Button component
     * */
    var MOD_NAME = 'workflow_design',
        $ = layui.jquery,
        api = layui.api,
        fast_config = layui.fast_config,
        utils = layui.utils,
        listeners = layui.listener,
        amis = layui.amis,
        pearTab = layui.tab
    ;


    /**
     * 保存流程模型监听器
     * 该监听器在资源工具栏中使用
     * @param {} event
     * @param {*} spanSchema
     * @param {*} toolbrObj
     */
    function saveWorkflowModelResourceToolbarListener(event, spanSchema, toolbrObj) {
        // debugger
        if(event.currentTarget.className.indexOf('save_disabled') > -1){
            return false
        }
        var div = pearTab.getActiveContent('#content')
        var activeIframe = $(div).children('div').children('iframe')[0]
        var iframeWindow = activeIframe.contentWindow

        var activeIframeId = activeIframe.valueOf().id
        var activeIframeSrc = activeIframe.valueOf().src
        console.log("activeIframeId=" + activeIframeId)
        console.log("activeIframeSrc=" + activeIframeSrc)

        var activeTabId = activeIframeId.split('_')[1] + '_' + activeIframeId.split('_')[2]
        console.log("activeTabId=" + activeTabId)

        // 获取流程模型发布状态
        var idDeployment = activeIframeSrc.split('/')[9]

        if ('N' === idDeployment) {
            layer.open({
                type: 1,
                title: '操作',
                shade: 0.3,
                content: ``,
                btn: ['保存', '升级', '取消'],
                btn1: function (index, layero) {
                    buttonAfterPoint(layero)
                    var flag = false
                    postMessage(flag)
                    // afterSave(flag, res)
                },
                btn2: function (index, layero) {
                    buttonAfterPoint(layero)
                    var flag = true
                    postMessage(flag)
                    // afterSave(flag, res)
                },
                btn3: function (index, layero) {
                    layer.closeAll();
                }

            });
        } else {
            layer.open({
                type: 1,
                title: '操作',
                shade: 0.3,
                content: ``,
                btn: ['升级', '取消'],
                btn1: function (index,layero) {
                    buttonAfterPoint(layero)
                    var flag = true
                    postMessage(flag)
                    // afterSave(flag, res)
                },
                btn3: function (index, layero) {
                    buttonAfterPoint(layero)
                    layer.closeAll();
                }
            });
        }

        // 点击按钮后按钮禁用
        function buttonAfterPoint(layero){
            $(layero[0].childNodes[3].childNodes[0]).addClass("layui-btn-disabled")
            $(layero[0].childNodes[3].childNodes[0]).attr("disabled", true);
        }

        // 调用流程设计器中的保存
        function postMessage(flag) {
            var res = null
            sessionStorage.setItem('workFlowModel', '')
            iframeWindow.globalSaveProcess(flag)
            var timer = setInterval(function () {
                res = sessionStorage.getItem('workFlowModel')
                if (res) {
                    clearInterval(timer)
                    afterSave(flag, res)
                }
            }, 200)
        }

        // 保存后操作
        function afterSave(flag, res) {
            // 根据返回数据判断是否成功
            console.log(res, 'res')
            if (res) {
                var resObj = JSON.parse(res)
                if (flag) {
                    // 刷新树
                    var data = {
                        id: resObj.id
                    };
                    // 关闭tab
                    // pearTab.delTabByElem('content', activeTabId)
                    console.log(data, "selectedNode")
                    // delete resource_tabs_obj.option.tabIdContentFn["#treenode_"+ node.tId];
                    // layui.resource_tree.selectedNode(data)
                    layui.resource_tree.closeTabAndOpenNew(resObj.id, activeTabId)

                }
                layer.closeAll();
                layer.alert("操作成功")
            } else {
                // layer.closeAll();
                layer.alert("操作失败")
            }

        }
    }

    function viewWorkflowModelResourceToolbarListener(event, spanSchema, toolbrObj){
        // debugger
        var div = pearTab.getActiveContent('#content')
        var activeIframe = $(div).children('div').children('iframe')[0]
        var iframeWindow = activeIframe.contentWindow
        iframeWindow.globalChangePreview()
        if($('.header-right-toolBar').find('.xml_active').length){
            $('.header-right-toolBar .xml_active').removeClass('xml_active'). addClass('workflow_active')
            $('.header-right-toolBar .save_active').removeClass('save_active'). addClass('save_disabled')
        }else{
            $('.header-right-toolBar .workflow_active').removeClass('workflow_active'). addClass('xml_active')
            $('.header-right-toolBar .save_disabled').removeClass('save_disabled'). addClass('save_active')
        }
    }

    function downloadWorkflowModelResourceToolbarListener(event, spanSchema, toolbrObj){
        // debugger
        var div = pearTab.getActiveContent('#content')
        var activeIframe = $(div).children('div').children('iframe')[0]
        var iframeWindow = activeIframe.contentWindow
        iframeWindow.globalExportSvgAction()
    }

    /**
     * 模块装配
     */
    function configur() {
        listeners.registerToolbarListener("saveWorkflowModelResourceToolbarListener", saveWorkflowModelResourceToolbarListener)
        listeners.registerToolbarListener("viewWorkflowModelResourceToolbarListener", viewWorkflowModelResourceToolbarListener)
        listeners.registerToolbarListener("downloadWorkflowModelResourceToolbarListener", downloadWorkflowModelResourceToolbarListener)
    }


    var workflow_design = function (opt) {
        this.option = opt;
    };


    /**
     * Button start loading
     * */
    workflow_design.prototype.render = function (opt) {
        var option = {
            elem: opt.elem,
            data: opt.data,
            treeNode: opt.treeNode,
            viewMode: opt.viewMode,
            pearBody: opt.pearBody,
            amisData: opt.amisData,
            callback: opt.callback,
        }

        return new workflow_design(option);
    }

    configur();
    exports(MOD_NAME, new workflow_design());

});
